/*
 * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.study.family.cdb;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.auth.AGConnectUser;
import com.huawei.agconnect.auth.ProfileRequest;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.squareup.picasso.Picasso;
import com.study.family.LoginActivity;
import com.study.family.R;
import com.study.family.third.HWIDActivity;

import java.util.ArrayList;
import java.util.List;

public class AboutMeFragment extends Fragment {

    private CdbActivity mActivity;

    ImageView imgViewPhoto;
    TextView txtViewUid;
    TextView txtViewNickName;
    TextView txtViewEmail;
    TextView txtViewPhone;
    Button btnSignOut;
    Button btnUpdateName;

    final String deufaultuser="游客";

    static Fragment newInstance() {
        return new AboutMeFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (CdbActivity) getActivity();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
      //   mActivity.getLoginHelper().addLoginCallBack(this);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_about_me, container, false);
        initUserDetailView(rootView);
        userShowInfo();
        return rootView;
    }

    private void userShowInfo() {
        AGConnectUser agConnectUser = AGConnectAuth.getInstance().getCurrentUser();
        String uid = agConnectUser.getUid();
        String nickname = agConnectUser.getDisplayName();
        String email = agConnectUser.getEmail();
        String phone = agConnectUser.getPhone();
        String photoUrl = agConnectUser.getPhotoUrl();
        txtViewUid.setText(uid);
        if(nickname==null)
          txtViewNickName.setText(deufaultuser);
        else
            txtViewNickName.setText(nickname);
        txtViewEmail.setText(email);
        txtViewPhone.setText(phone);
        if (!TextUtils.isEmpty(photoUrl)) {
            Picasso.get().load(photoUrl).into(imgViewPhoto);
        }
    }



    private void initUserDetailView(View rootView) {

        imgViewPhoto = rootView.findViewById(R.id.imgView_photo);
        imgViewPhoto.setOnClickListener(v->updateAvatar());
        txtViewUid = rootView.findViewById(R.id.txtView_uid);
        txtViewNickName = rootView.findViewById(R.id.txtView_NickName);
        txtViewEmail = rootView.findViewById(R.id.txtView_email);
        txtViewPhone = rootView.findViewById(R.id.txtView_phone);
        btnUpdateName = rootView.findViewById(R.id.btn_update_name);
        btnUpdateName.setOnClickListener(v->updateDisplayName());

        btnSignOut = rootView.findViewById(R.id.btn_Signout);
        btnSignOut.setOnClickListener(v->signout());

        rootView.findViewById(R.id.btn_link).setOnClickListener(v->link());

        AGConnectUser agConnectUser = AGConnectAuth.getInstance().getCurrentUser();
        String nickname = agConnectUser.getDisplayName();
        String phone = agConnectUser.getPhone();
        if((phone!=null)) {
            btnUpdateName.setVisibility(View.VISIBLE);
            rootView.findViewById(R.id.btn_link).setVisibility(View.INVISIBLE);
        }


    }

    private void updateAvatar() {
        update(new UpdateCallback() {
            @Override
            public void onUpdate(String data) {
                if (AGConnectAuth.getInstance().getCurrentUser() != null) {
                    // create a profileRequest
                    ProfileRequest userProfile = new ProfileRequest.Builder()
                            .setPhotoUrl(data)
                            .build();
                    // update profile
                    AGConnectAuth.getInstance().getCurrentUser().updateProfile(userProfile)
                            .addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    userShowInfo();
                                }
                            })
                            .addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(Exception e) {
                                    Toast.makeText(getContext(), "更新头像失败:" + e, Toast.LENGTH_SHORT).show();
                                }
                            });
                }
            }
        });
    }

    private void updateDisplayName() {
        update(new UpdateCallback() {
            @Override
            public void onUpdate(String data) {
                if (AGConnectAuth.getInstance().getCurrentUser() != null) {
                    // create a profileRequest
                    ProfileRequest userProfile = new ProfileRequest.Builder()
                            .setDisplayName(data)
                            .build();
                    // update profile
                    AGConnectAuth.getInstance().getCurrentUser().updateProfile(userProfile)
                            .addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    userShowInfo();
                                }
                            })
                            .addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(Exception e) {
                                    Toast.makeText(getContext(), "更新昵称失败:" + e, Toast.LENGTH_SHORT).show();
                                }
                            });
                }
            }
        });
    }

    private void link() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_link, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(getContext()).setView(view).create();
        ListView listView = view.findViewById(R.id.list_view);
        List<LinkEntity> linkEntityList = initLink();
        LinkAdapter linkAdapter = new LinkAdapter(dialog.getContext(), R.layout.list_link_item, linkEntityList, new CdbActivity.LinkClickCallback() {
            @Override
            public void click() {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        listView.setAdapter(linkAdapter);
        dialog.show();
    }

    private List<LinkEntity> initLink() {
        List<LinkEntity> linkEntityList = new ArrayList<>();
        linkEntityList.add(new LinkEntity("华为ID", R.mipmap.huawei, HWIDActivity.class));
        //linkEntityList.add(new LinkEntity("手机", R.mipmap.huawei, PhoneActivity.class));

        return linkEntityList;
    }

    private void signout() {
        if (AGConnectAuth.getInstance().getCurrentUser() != null) {
            // signOut
            AGConnectAuth.getInstance().signOut();
            startActivity(new Intent(getActivity(), LoginActivity.class));

            mActivity.finish();
        }
    }
    private void update(final UpdateCallback callback) {
        LinearLayout layout = new LinearLayout(getContext());
        layout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        layout.setOrientation(LinearLayout.VERTICAL);
        final EditText editText = new EditText(getContext());
        layout.addView(editText);
        AlertDialog.Builder dialogBuilder =
                new AlertDialog.Builder(getContext()).setTitle("更新");
        dialogBuilder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // input photoUrl or display name
                String data = editText.getText().toString().trim();
                if (!TextUtils.isEmpty(data)) {
                    callback.onUpdate(data);
                }
            }
        });
        dialogBuilder.setView(layout);
        dialogBuilder.show();
    }

    interface UpdateCallback {
        void onUpdate(String data);
    }
}
